package com.skivingcloud.admin.sys.service.impl;

import com.skivingcloud.admin.sys.entity.SysOrg;
import com.skivingcloud.admin.sys.entity.Tenant;
import com.skivingcloud.admin.sys.entity.TenantMenu;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.sys.mapper.SysOrgMapper;
import com.skivingcloud.admin.sys.mapper.TenantMapper;
import com.skivingcloud.admin.sys.mapper.TenantMenuMapper;
import com.skivingcloud.admin.sys.service.ITenantService;
import com.skivingcloud.common.contants.Constant;
import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.StringUtils;
import com.skivingcloud.common.utils.TreeUtils;
import com.skivingcloud.common.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONObject;

/**
 * <p>
 * 租户表 服务实现类
 * </p>
 *
 * @author skivingcloud
 * @since 2022-01-28
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

	@Autowired
	private TenantMapper tenantMapper;
	@Autowired
	private SysOrgMapper sysOrgMapper;
	@Autowired
	private TenantMenuMapper tenantMenuMapper;
	@Override
	public String getTenantIdByCode(String tenantCode) {
		QueryWrapper<Tenant> queryWrapper = new QueryWrapper<Tenant>();
		queryWrapper.eq("tenant_code", tenantCode);
		List<Tenant> ts = tenantMapper.selectList(queryWrapper);
		return ts.isEmpty() ? null : ts.get(0).getId();
	}

	/**
	 * 查询租户信息{key:'', value:''}
	 * 
	 * @return
	 */
	@Override
	public List<Map<String, Object>> getTenantSelect() {
		return tenantMapper.getTenantSelect();
	}

	/**
	 * 分页查询
	 * 
	 * @param params
	 * @return
	 */
	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		PageUtils pageUtils = PageUtils.getPageInfo(params);
		Page<Tenant> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
		Tenant tenant = (Tenant) JSONObject.toBean(JSONObject.fromObject(params.get("dataForm")), Tenant.class);
		QueryWrapper<Tenant> queryWrapper = new QueryWrapper<Tenant>();
		if (StringUtils.isNotBlank(tenant.getTenantCode())) {
			queryWrapper.like("tenant_code", "%" + tenant.getTenantCode().trim() + "%");
		}
		if (StringUtils.isNotBlank(tenant.getTenantName())) {
			queryWrapper.like("tenant_name", "%" + tenant.getTenantName().trim() + "%");
		}
		queryWrapper.orderByDesc("mod_time");
		List<Tenant> list = tenantMapper.selectList(queryWrapper);
		pageUtils = new PageUtils(p);
		return pageUtils;
	}

	/**
	 * 更新
	 * 
	 * @param tenant
	 * @param user
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void update(Tenant tenant, User user) {
		LocalDateTime nowDate = LocalDateTime.now();
		tenant.setModTime(nowDate);
		tenant.setModUser(user.getId());
		tenantMapper.updateById(tenant);
	}

	/**
	 * 新增
	 * 
	 * @param tenant
	 * @param user
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void save(Tenant tenant, User user) {
		LocalDateTime nowDate = LocalDateTime.now();
		tenant.setId(UuidUtil.get32UUID());
		tenant.setCreateTime(nowDate);
		tenant.setModTime(nowDate);
		tenant.setCreater(user.getId());
		tenant.setModUser(user.getId());
		tenantMapper.insert(tenant);
		// 创建租户时为该租户创建顶级组织机构
		SysOrg org = new SysOrg();
		org.setId(UuidUtil.get32UUID());
		org.setCreater(user.getId());
		org.setCreateTime(nowDate);
		org.setIsParent(Constant.COMMON_YES_OR_NO_YES);
		org.setOrdernum(0);
		org.setOrgCode(tenant.getTenantCode());
		org.setOrgLevel(1);
		org.setOrgName(tenant.getTenantName());
		org.setOrgRank(Constant.OrgRank.ORGRANK_COMPANY.getValue());
		org.setOrgStatus(Constant.COMMON_STATUS_NORMAL);
		org.setOrgType(Constant.OrgType.ORGRANK_PRACTICAL.getValue());
		org.setParentId("0");
		org.setShortName(tenant.getTenantName());
		org.setTenantId(tenant.getId());
		org.setVersion(0);
		sysOrgMapper.insert(org);
	}

	/**
	 * 批量删除
	 * 
	 * @param roleIds
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String[] roleIds) {
		tenantMapper.deleteBatchIds(Arrays.asList(roleIds));
	}

	/**
	 * 根据租户id获取租户的资源权限范围
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public List<TenantMenu> getResTreeByTenantId(String id) {
		QueryWrapper<TenantMenu> queryWrapper = new QueryWrapper<TenantMenu>();
		queryWrapper.eq("tenant_id", id);
		return tenantMenuMapper.selectList(queryWrapper);
	}

	/**
	 * 设置租户资源范围
	 * 
	 * @param tenant
	 * @param user
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
    public void setSysTenantMenu(Tenant tenant, User user) {
		// 先删除租户资源关联再增加，非超级管理员不能操作
		if (user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			QueryWrapper<TenantMenu> queryWrapper = new QueryWrapper<TenantMenu>();
			queryWrapper.eq("tenant_id", tenant.getId());
			tenantMenuMapper.delete(queryWrapper);
		} else {
			throw new BusinessException("权限不足，只有超级管理员能操作");
		}
		for (String resid : tenant.getResId()) {
			TenantMenu rm = new TenantMenu();
			rm.setId(UuidUtil.get32UUID());
			rm.setMenuId(resid);
			rm.setTenantId(tenant.getId());
			tenantMenuMapper.insert(rm);
		}
	}

	/**
	 * 根据租户加载资源树权限
	 * 
	 * @param tenantId
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<TreeUtils> getTenantRoleResTree(String tenantId) throws Exception {
		List<Map<String, Object>> list = tenantMenuMapper.getTenantResTree(tenantId);
		List<TreeUtils> treeList = TreeUtils.getTreeListMap(list, "id", "parent_id", "name", null, null);
		return treeList;
	}
}
